/**
 * Middleware to track API request statistics
 */

function createStatsMiddleware(statsTracker) {
    return async function statsMiddleware(req, res, next) {
        // Skip stats endpoints and static resources
        if (req.path.startsWith('/api/stats') || 
            req.path.startsWith('/monitor') ||
            req.path.startsWith('/stats-dashboard') ||
            req.path.endsWith('.html') ||
            req.path.endsWith('.js') ||
            req.path.endsWith('.css')) {
            return next();
        }

        const startTime = Date.now();
        const requestSize = JSON.stringify(req.body || {}).length;
        
        // Get username from various sources
        let username = 'anonymous';
        
        // Try to get username from user auth
        if (req.user && req.user.name) {
            username = req.user.name;
        }
        // Try to get from basic auth
        else if (req.headers.authorization && req.headers.authorization.startsWith('Basic ')) {
            const credentials = Buffer.from(req.headers.authorization.slice(6), 'base64').toString();
            username = credentials.split(':')[0];
        }
        // Try to get from token header
        else if (req.headers['x-user-token']) {
            // This would need to be matched against user list
            username = req.headers['x-user-token'].substring(0, 8) + '...';
        }
        // Use IP as fallback
        else {
            username = req.ip || req.connection.remoteAddress || 'unknown';
        }

        // Store original end function
        const originalEnd = res.end;
        let responseSize = 0;

        // Override end function to capture response
        res.end = function(chunk, encoding) {
            // Calculate response size
            if (chunk) {
                responseSize = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk, encoding);
            }

            // Call original end
            originalEnd.call(this, chunk, encoding);

            // Track statistics after response is sent
            const duration = Date.now() - startTime;
            const success = res.statusCode >= 200 && res.statusCode < 400;
            
            statsTracker.trackRequest(username, {
                success,
                duration,
                requestSize,
                responseSize,
                statusCode: res.statusCode,
                endpoint: req.path,
                error: !success ? res.statusMessage || 'Request failed' : null
            }).catch(error => {
                console.error('Error tracking request stats:', error);
            });
        };

        next();
    };
}

export { createStatsMiddleware };